package com.project.class9_1.three.dao;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class DaoFactory {
    private static Map<String,Object> daoMap = new HashMap<>();
    static {
        //得到dao实现类的目录文件对象
        File file = new File("src/main/java/com/project/class9_1/three/dao/impl");
        //得到目录中所有的文件
        File[] fileArray = file.listFiles();
        try {
            for (File f : fileArray) {
                //判断文件对象是否以.java结尾
                if (f.isFile() && f.getName().endsWith(".java")) {
                    //得到文件夹中文件的类全路径
                    String classPath = "com.project.class9_1.three.dao.impl." +
                            f.getName().substring(0, f.getName().lastIndexOf(".java"));
                    //加载类，得到类模版
                    Class c = Class.forName(classPath);
                    //调用无参构造方法，返回DAO对象
                    Object daoObj = c.getConstructor().newInstance();
                    //得到该类实现的接口列表
                    Class[] interfaceClassArray = c.getInterfaces();
                    if(interfaceClassArray.length == 1){
                        daoMap.put(interfaceClassArray[0].getSimpleName(),daoObj);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static Object getDao(String interfaceName){
        return daoMap.get(interfaceName);
    }

}
